﻿#if !NETCOREAPP2_0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SAM.Framework.ILicence;
using SAM.Framework.ILicence.Models;
using SAM.Framework.Machine;
using Newtonsoft.Json;

namespace SAM.Framework.LicenceRepositories
{
    public class RegistryRepository : ILicenceRepository
    {
        private IRegistryProvider registryProvider;
        /// <summary>
        /// 写入注册表的分类Key
        /// </summary>
        private Microsoft.Win32.RegistryKey registryKey = Microsoft.Win32.Registry.LocalMachine;
        /// <summary>
        /// 授权或机器码存放的位置
        /// </summary>
        private string licPath = @"System\Software\Microsoft\SAMFramework";

        /// <summary>
        /// 机器码的Key
        /// </summary>
        private string MachineKey = "MachineKey";

        /// <summary>
        /// 授权信息的Key
        /// </summary>
        private string AuthorizationKey = "AuthorizationKey";

        public RegistryRepository(IRegistryProvider registryProvider)
        {
            this.registryProvider = registryProvider;
        }

        public T ReadAuthorizationInfo<T>() where T : AuthorizationInfo
        {
            string text = this.registryProvider.GetRegistryData(registryKey, licPath, AuthorizationKey);
            if (string.IsNullOrEmpty(text)) return default(T);
            return this.Deserialize<T>(text);
        }

        public T ReadMachineCodeInfo<T>() where T : MachineCodeInfo
        {
            string text = this.registryProvider.GetRegistryData(registryKey, licPath, MachineKey);
            if (string.IsNullOrEmpty(text)) return default(T);
            return this.Deserialize<T>(text);
        }

        public bool Save(AuthorizationInfo authorizationInfo)
        {
            this.registryProvider.SetRegistryData(registryKey, licPath, AuthorizationKey, this.Serialize<AuthorizationInfo>(authorizationInfo));
            return true;
        }

        public bool Save(MachineCodeInfo machineCodeInfo)
        {
            this.registryProvider.SetRegistryData(registryKey, licPath, MachineKey, this.Serialize<MachineCodeInfo>(machineCodeInfo));
            return true;
        }

        private string Serialize<T>(T obj)
        {
            string content = JsonConvert.SerializeObject(obj);
            return content;
        }
        private T Deserialize<T>(string content)
        {
            T retObj = default(T);
            retObj = JsonConvert.DeserializeObject<T>(content);
            return retObj;
        }
    }
}
#endif
